"use client"

import { createContext, useContext, useState, useEffect, type ReactNode } from "react"
import { type Locale, translations, type Dictionary } from "@/lib/i18n"

interface LanguageContextType {
  locale: Locale
  setLocale: (locale: Locale) => void
  dictionary: Dictionary
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined)

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [locale, setLocaleState] = useState<Locale>("en") // Default to English

  useEffect(() => {
    // Try to load locale from localStorage
    const savedLocale = localStorage.getItem("locale") as Locale
    if (savedLocale && translations[savedLocale]) {
      setLocaleState(savedLocale)
    } else {
      // Detect browser language if no saved locale
      const browserLanguage = navigator.language.split("-")[0]
      if (browserLanguage === "zh") {
        setLocaleState("zh")
      } else {
        setLocaleState("en")
      }
    }
  }, [])

  const setLocale = (newLocale: Locale) => {
    if (translations[newLocale]) {
      setLocaleState(newLocale)
      localStorage.setItem("locale", newLocale)
    }
  }

  const dictionary = translations[locale] || translations["en"]

  return <LanguageContext.Provider value={{ locale, setLocale, dictionary }}>{children}</LanguageContext.Provider>
}

export function useLanguage() {
  const context = useContext(LanguageContext)
  if (context === undefined) {
    throw new Error("useLanguage must be used within a LanguageProvider")
  }
  return context
}
